import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ActivatedRoute, Router} from '@angular/router';
import {GnDigestUtils, GnForm, GnJsonUtils, GnMessageService, GnSiteInfo} from "geminis-ng";
import {Config} from "../api/Config";
import {LoginUser} from "../api";

@Component({
  selector: 'gn-resources-login',
  templateUrl: './login.component.html'
})
export class LoginComponent extends GnForm implements OnInit {

  code: string;
  imageUrl = '';
  error: string;

  constructor(private httpClient: HttpClient,
              private loginUser: LoginUser,
              private messageService: GnMessageService,
              public siteInfo: GnSiteInfo,
              public config: Config,
              private router: Router,
              private activatedRoute: ActivatedRoute) {
    super();

    activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.msg) {
        this.setError(queryParams.msg, queryParams.msg);
      }
    });
  }

  ngOnInit(): void {
    this.refreshCode();
    this.loginUser.clean();
  }

  refreshCode() {
    this.httpClient.get('/RESOURCES-SERVICE/login/code', {responseType: 'text'})
      .subscribe((data: any) => {
        this.code = data;
        this.imageUrl = '/RESOURCES-SERVICE/login/codeImage/' + this.code;
      });
  }

  loginPwd(): void {
    this.error = null;
    this.messageService.success('登录中...');
    let loginValue = this.form.formGroup.value;

    loginValue.codeToken = this.code;
    GnDigestUtils.sha256(loginValue.password)
      .then((value => {
        loginValue.password = value;
        loginValue = GnJsonUtils.obj2FormData(loginValue);

        this.httpClient.post('/RESOURCES-SERVICE/login/pwd', loginValue, {observe: 'response'})
          .subscribe((resp: any) => {
              resp.body.id = resp.body.username;
              this.loginUser.setValue(resp.body);
              this.loginUser.jwt = resp.headers.get("Authorization");
              this.loginUser.jwtExpire = resp.headers.get("Authorization-Expire");
              this.loginUser.isLogin = true;
              this.loginUser.save();
              this.messageService.success('登录成功，正在跳转');

              this.siteInfo.filterMenu(this.loginUser.authorities.map(value => value.authority));

              if (!this.siteInfo.menu || this.siteInfo.menu.length === 0) {
                this.setError('没有可访问的功能', '没有可访问的功能');
                return;
              }

              let item = this.siteInfo.menu[0];
              while (!item.routerLink && item.items && item.items.length > 0) {
                item.expanded = true;
                item = item.items[0];
              }
              item.expanded = true;
              const url = item.routerLink.toString();
              this.router.navigate([url]);
            },
            (error) => {
              this.setError('登录失败', error.error.message ? error.error.message : error.message);
            });
      }));
  }

  private setError(error: string, detail: string): void {
    this.messageService.error({message: error, error: {message: detail}});
    this.refreshCode();
  }

}
